#include <func.h>
#include"train.h"
/*
//3.1 接收文件的名字
int length;
int ret = recv(clientfd, &length, 4, MSG_WAITALL);
printf(">>1. filename length:%d\n", length);

//提出新的需求: 需要接收确定字节数的数据
char recvBuff[1000] = {0};//应用层接收缓冲区
ret = recv(clientfd, recvBuff, length, MSG_WAITALL); printf(">>2. recv filename:%s\n", recvBuff);

//3.2 在客户端本地，要创建文件
int fileFd = open(recvBuff, O_CREAT|O_RDWR, 0644);
//3.3 接收文件的大小
off_t fileSize;
ret = recv(clientfd, &length, 4, MSG_WAITALL);
printf("length: %d\n", length);
ret = recv(clientfd, &fileSize, sizeof(fileSize), MSG_WAITALL);
printf("> file length: %ld\n", fileSize);

ftruncate(fileFd, fileSize);

//3.4 接收文件的内容
char * pbuf = (char*) mmap(NULL, fileSize, 
PROT_READ|PROT_WRITE, 
MAP_SHARED, fileFd, 0);
ret = recv(clientfd, pbuf, fileSize, MSG_WAITALL);

printf("recv file success\n");
printf("---------------------\n");

close(fileFd);
munmap(pbuf, fileSize);
*/
void recv_file(int sfd, char *filename)
{
    train_t train;
    memset(&train, 0, sizeof(train));
    printf("start recv_file\n");
    printf("---filename is %s\n",filename);

    recvn(sfd, &train.length, 4);
    printf("train.len=%d\n", train.length);
    if (train.length == -1)
    {
        printf("--server not have: %s--\n",filename);
        return;

    }
    memset(&train, 0, sizeof(train));
    int fd = open(filename, O_CREAT | O_RDWR | O_APPEND, 0666);
    if (fd == -1)
    {
        printf("open error\n");
        return;

    }
    memset(&train, 0, sizeof(train));
    off_t filesize;
    recvn(sfd, &train.length, sizeof(train.length));
    recvn(sfd, &filesize, train.length);
    int left = filesize, cur = 0, ret = 0;
    while (left > 0)
    {
        memset(&train, 0, sizeof(train));
        recvn(sfd, &train.length, 4);
        recvn(sfd, train.data, train.length);
        ret = write(fd, train.data, train.length);
        if (ret == -1)
        {
            printf("write error\n");
            return;

        }
        cur += ret;
        left -= ret;

    }
    printf("recv file success\n");

}




